package org.ptkparty.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.HasEditorErrors;
import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.editor.client.adapters.TakesValueEditor;
import com.google.gwt.editor.ui.client.adapters.ValueBoxEditor;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiChild;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.ValueBoxBase;
import com.google.gwt.user.client.ui.Widget;

public class CustomValueListBoxEditorDecorator<T> extends Composite implements HasEditorErrors<T>, IsEditor<TakesValueEditor<T>> {

	private static CustomValueListBoxEditorDecoratorUiBinder uiBinder = GWT.create(CustomValueListBoxEditorDecoratorUiBinder.class);

	interface CustomValueListBoxEditorDecoratorUiBinder extends UiBinder<Widget, CustomValueListBoxEditorDecorator<?>> {
	}

	@UiField
	DivElement divElement;

	@UiField
	SimplePanel contents;

	@UiField
	DivElement errorLabel;

	private TakesValueEditor<T> editor;

	@UiConstructor
	public CustomValueListBoxEditorDecorator() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public CustomValueListBoxEditorDecorator(ValueBoxBase<T> widget, ValueBoxEditor<T> editor) {
		this();
		contents.add(widget);
		this.editor = editor;
	}

	@Override
	public TakesValueEditor<T> asEditor() {
		return editor;
	}

	public void setEditor(ValueBoxEditor<T> editor) {
		this.editor = editor;
	}

	@UiChild(limit = 1, tagname = "valueListBox")
	public void setValueListBox(ValueBoxBase<T> widget) {
		contents.add(widget);
		setEditor(widget.asEditor());
	}

	@Override
	public void showErrors(List<EditorError> errors) {
		StringBuilder sb = new StringBuilder();
		for (EditorError error : errors) {
			if (error.getEditor().equals(editor)) {
				sb.append("\n").append(error.getMessage());
			}
		}

		if (sb.length() == 0) {
			errorLabel.setInnerText("");
			errorLabel.getStyle().setDisplay(Display.NONE);
			divElement.setClassName("");
			return;
		}

		errorLabel.setInnerText(sb.substring(1));
		errorLabel.getStyle().setDisplay(Display.INLINE_BLOCK);
		divElement.setClassName("invalid");
	}
}
